/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Slave;

import Core.MessageBuilder;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author Mr Bao
 */
public class MasterPinger extends TimerTask {

    private Timer timer;
    private static long duration = 0L;
    private static long delay = 0L;
    private static String masterAddress;
    private static int masterPort;
    private SlaveInfo slaveInfo;
    private boolean keepGoing = true;
    private Hashtable users = new Hashtable();

    public void LoadConfigure() {
        duration = 5 * 1000;
        delay = 5 * 1000;
        masterAddress = "localhost";
        masterPort = 1009;
    }

    public MasterPinger(Hashtable users, SlaveInfo slaveInfo) {
        LoadConfigure();
        this.users = users;
        this.slaveInfo = slaveInfo;
        timer = new Timer();
        timer.scheduleAtFixedRate(this, delay, duration);
    }

    @Override
    public void run() {
        PrintStream out = null;
        Socket slave = null;
        try {
            try {
                slave = new Socket(masterAddress, masterPort);
            } catch (Exception e) {
                keepGoing = false;
            }
            if (keepGoing) {
                long numberConnections = 0L;
                synchronized (users) {
                    numberConnections = users.size();
                }
                slaveInfo.setCurrentConnections(numberConnections);
                String reportMessage = MessageBuilder.BuildRerportMessage(slaveInfo);
                out = new PrintStream(slave.getOutputStream());
                out.println(reportMessage);
            }
        } catch (Exception e) {
        } finally {
            if (out != null) {
                out.close();
            }
            if (slave != null) {
                slave = null;
            }
        }
    }
}
